import { forwardRef, useImperativeHandle, useRef } from "react";

//forwardRef函数，用于获取子组件中的DOM元素
const Son=forwardRef((props,ref)=>{
  const inputRef=useRef(null)
  const focusHandler=()=>{
    inputRef.current.focus()
  }
  //useImperativeHandle钩子函数，用于让父组件获取子组件的方法
  useImperativeHandle(ref,()=>{
    return {
      focusHandler
    }
  })
  return <input ref={inputRef}/>
})
function App() {
  const sonRef=useRef(null)
  return (
    <div className="App">
      <Son ref={sonRef}/>
      <button onClick={() =>sonRef.current.focusHandler() }>点击让子组件input框聚焦</button>
    </div>
  );
}

export default App;
